/*
 * MIT License
 *
 * Copyright (c) 2023 北京凯特伟业科技有限公司
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */
package com.je.bpm.engine.impl.bpmn.deployer;

import com.je.bpm.core.model.EventDefinition;
import com.je.bpm.core.model.FlowElement;
import com.je.bpm.core.model.TimerEventDefinition;
import com.je.bpm.core.model.event.StartEvent;
import com.je.bpm.engine.ProcessEngineConfiguration;
import com.je.bpm.engine.impl.asyncexecutor.JobManager;
import com.je.bpm.engine.impl.cmd.CancelJobsCmd;
import com.je.bpm.engine.impl.context.Context;
import com.je.bpm.engine.impl.jobexecutor.TimerEventHandler;
import com.je.bpm.engine.impl.jobexecutor.TimerStartEventJobHandler;
import com.je.bpm.engine.impl.persistence.entity.ProcessDefinitionEntity;
import com.je.bpm.engine.impl.persistence.entity.TimerJobEntity;
import com.je.bpm.engine.impl.util.CollectionUtil;
import com.je.bpm.core.model.process.Process;

import java.util.ArrayList;
import java.util.List;

/**
 * Manages timers for newly-deployed process definitions and their previous versions.
 */
public class TimerManager {

    protected void removeObsoleteTimers(ProcessDefinitionEntity processDefinition) {
        List<TimerJobEntity> jobsToDelete = null;

        if (processDefinition.getTenantId() != null && !ProcessEngineConfiguration.NO_TENANT_ID.equals(processDefinition.getTenantId())) {
            jobsToDelete = Context.getCommandContext().getTimerJobEntityManager().findJobsByTypeAndProcessDefinitionKeyAndTenantId(
                    TimerStartEventJobHandler.TYPE, processDefinition.getKey(), processDefinition.getTenantId());
        } else {
            jobsToDelete = Context.getCommandContext().getTimerJobEntityManager()
                    .findJobsByTypeAndProcessDefinitionKeyNoTenantId(TimerStartEventJobHandler.TYPE, processDefinition.getKey());
        }

        if (jobsToDelete != null) {
            for (TimerJobEntity job : jobsToDelete) {
                new CancelJobsCmd(job.getId()).execute(Context.getCommandContext());
            }
        }
    }

    protected void scheduleTimers(ProcessDefinitionEntity processDefinition, Process process) {
        JobManager jobManager = Context.getCommandContext().getJobManager();
        List<TimerJobEntity> timers = getTimerDeclarations(processDefinition, process);
        for (TimerJobEntity timer : timers) {
            jobManager.scheduleTimerJob(timer);
        }
    }

    protected List<TimerJobEntity> getTimerDeclarations(ProcessDefinitionEntity processDefinition, Process process) {
        JobManager jobManager = Context.getCommandContext().getJobManager();
        List<TimerJobEntity> timers = new ArrayList<TimerJobEntity>();
        if (CollectionUtil.isNotEmpty(process.getFlowElements())) {
            for (FlowElement element : process.getFlowElements()) {
                if (element instanceof StartEvent) {
                    StartEvent startEvent = (StartEvent) element;
                    if (CollectionUtil.isNotEmpty(startEvent.getEventDefinitions())) {
                        EventDefinition eventDefinition = startEvent.getEventDefinitions().get(0);
                        if (eventDefinition instanceof TimerEventDefinition) {
                            TimerEventDefinition timerEventDefinition = (TimerEventDefinition) eventDefinition;
                            TimerJobEntity timerJob = jobManager.createTimerJob(timerEventDefinition, false, null, TimerStartEventJobHandler.TYPE,
                                    TimerEventHandler.createConfiguration(startEvent.getId(), timerEventDefinition.getEndDate(), timerEventDefinition.getCalendarName()));

                            if (timerJob != null) {
                                timerJob.setProcessDefinitionId(processDefinition.getId());

                                if (processDefinition.getTenantId() != null) {
                                    timerJob.setTenantId(processDefinition.getTenantId());
                                }
                                timers.add(timerJob);
                            }

                        }
                    }
                }
            }
        }

        return timers;
    }
}
